package com.gwsdk.paysdk.dialog.realname;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gwsdk.open.AuthenticationResult;
import com.gwsdk.open.GWApi;
import com.gwsdk.paysdk.acitvityV2.GWPayActivity;
import com.gwsdk.paysdk.utils.GWLog;
import com.gwsdk.paysdk.utils.ToastUtil;
import com.gwsdk.paysdk.bean.AntiAddictionModel;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.entity.AntiAddiction;
import com.gwsdk.paysdk.entity.ChannelAndGameinfo;
import com.gwsdk.paysdk.http.process.AntiAddictionProgress;
import com.gwsdk.paysdk.http.process.CertificateProcess;
import com.gwsdk.paysdk.http.process.UserInfoProcess;
import com.gwsdk.paysdk.listener.OnMultiClickListener;
import com.gwsdk.paysdk.utils.AppUtils;
import com.gwsdk.paysdk.utils.GWInflaterUtils;
import com.gwsdk.paysdk.utils.TextUtils;



public class GWCertificationDialog extends Dialog {

    private String TAG = "GWCertificationDialog";
    private  String name = "";
    private  String idcard = "";
    private final Context context;
    private LayoutInflater inflater;
    private View view;
    private EditText edtName;
    private EditText edtIdCard;
    private TextView btnOk;
    private TextView tvMsg;
    private ImageView btnClose;
    private String msg = "";
    private boolean isJumpPay = false; //认证完是否跳转到支付界面（支付前弹出的认证）

    public GWCertificationDialog(@NonNull Context context, String msg, boolean jumpPay) {
        super(context, GWInflaterUtils.getIdByName(context,"style","gw_certificationTypeDialog"));
        this.context = context;
        this.msg = msg;
        isJumpPay = jumpPay;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        inflater = LayoutInflater.from(context);
        view = inflater.inflate(GWInflaterUtils.getLayout(context,"gw_dialog_certification"), null);
        setContentView(view);
        edtName = findViewById(GWInflaterUtils.getControl(context,"mch_edt_name"));
        edtIdCard = findViewById(GWInflaterUtils.getControl(context,"mch_edt_idcard"));
        btnOk = findViewById(GWInflaterUtils.getControl(context,"mch_btn_ok"));
        btnClose = findViewById(GWInflaterUtils.getControl(context,"mch_btn_close"));
        btnClose.setVisibility(View.INVISIBLE);
        tvMsg = findViewById(GWInflaterUtils.getControl(context,"mch_tv_msg"));
        tvMsg.setMovementMethod(ScrollingMovementMethod.getInstance());//文字超出可滑动
        btnOk.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                toCertification();
            }
        });

        if (!TextUtils.isEmpty(msg)){
            tvMsg.setText(msg);
        }

        setCancelable(false);
    }

    //提交认证
    private void toCertification(){
        name = edtName.getText().toString();
        idcard = edtIdCard.getText().toString();

        if (isTure(name,idcard)){
            CertificateProcess process = new CertificateProcess();
            process.setReal_name(name);
            process.setIdcard(idcard);
            process.post(mHandler);
        }
    }

    /**
     * 获取用户信息
     */
    private void quereUserInfo() {
        UserInfoProcess userInfoProcess = new UserInfoProcess();
        userInfoProcess.post(mHandler);
    }

    /**
     * 请求防沉迷信息
     */
    private void getAntiAddictionInfo(){
        AntiAddictionProgress antiAddictionProgress = new AntiAddictionProgress();
        antiAddictionProgress.setGet_talking_code(0);
        antiAddictionProgress.post(mHandler);
    }

    /**
     * 请求返回
     */
    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constant.To_Certificate_SUCCESS:
                    if (AntiAddictionModel.myTimeUtil != null){
                        AntiAddictionModel.myTimeUtil.Stop();
                    }
                    ToastUtil.show(context, "实名认证成功");
                    quereUserInfo();
                    break;

                case Constant.To_Certificate_WAITING:  //认证等待中..
                    if (!TextUtils.isEmpty((String)msg.obj)){
                        ToastUtil.show(context, (String) msg.obj);
                    }
                    dismiss();
                    break;

                case Constant.To_Certificate_FAIL:
                    if (!TextUtils.isEmpty((String)msg.obj)){
                        ToastUtil.show(context, (String) msg.obj);
                    }
                    break;

                case Constant.GET_USER_INFO_SUCCESS:// 获取用户信息
                    ChannelAndGameinfo info = (ChannelAndGameinfo) msg.obj;
                    if (info.getAge_status().equals("1") && !android.text.TextUtils.isEmpty(info.getIdcard())){
                        AuthenticationResult result = new AuthenticationResult();
                        result.AgeStatus = Integer.valueOf(info.getAge_status());
                        result.UserBirthday = AppUtils.getBirthday(info.getIdcard());
                        if (GWApi.getApi().getRealNameAuthenticationCallback() != null){
                            GWApi.getApi().getRealNameAuthenticationCallback().authenticationResult(result);
                        }
                    }
                    if(info.getAge_status().equals("2")){
                        if (AntiAddictionModel.myTimeUtil != null){
                            AntiAddictionModel.myTimeUtil.Stop();
                        }
                    }

                    if (info.getAge_status().equals("3")){ //未成年,查询防沉迷时间
                        getAntiAddictionInfo();
                    }

                    dismiss();
                    break;
                case Constant.GET_USER_INFO_FAIL:
                    String tip = (String) msg.obj;
                    ToastUtil.show(context, "获取用户信息失败："+tip);
                    break;

                case Constant.REQUEST_ANTI_ADDICTION_SUCCESS:
                    final AntiAddiction antiAddiction = (AntiAddiction) msg.obj;
                    if (antiAddiction == null) {
                        GWLog.e(TAG, "msg.obj is null");
                        return;
                    }
                    if (antiAddiction.getAge_status() == 2) {
                        GWLog.w(TAG, "玩家已认证并且已成年，不进入防沉迷限制");
                        AntiAddictionModel.getInstance().stopGameTimer();
                        AntiAddictionModel.getInstance().stopTime(true);
                    }else {
                        Constant.userIsOnLine = false;
                        AntiAddictionModel.getInstance().requestAntiAddictionInfo(GWApi.getApi().getContext()); //用户上线，查询防沉迷信息
                    }

                    if (isJumpPay){
                        Intent intent = new Intent(context, GWPayActivity.class);
                        context.startActivity(intent);
                    }
                    break;

                case Constant.REQUEST_ANTI_ADDICTION_FAIL:
                    String tips = (String) msg.obj;
                    ToastUtil.show(context, "请求防沉迷信息失败："+tips);
                    if (isJumpPay){
                        Intent intent = new Intent(context, GWPayActivity.class);
                        context.startActivity(intent);
                    }
                    break;
            }
        }
    };

    /**
     * 验证姓名  身份证号是否正确
     * @return
     */
    private boolean isTure(String name,String idcard) {
        if (TextUtils.isEmpty(name)) {
            ToastUtil.show(context, "姓名不能为空");
            return false;
        }

        if (name.length()<2 || name.length()>25){
            ToastUtil.show(context, "姓名长度需要在2-25个字符之间");
            return false;
        }
        if (!name.matches(Constant.REGULAR_NAME)) {
            ToastUtil.show(context, "姓名格式错误");
            return false;
        }
        if (TextUtils.isEmpty(idcard)) {
            ToastUtil.show(context, "身份证号不能为空");
            return false;
        }
        if (idcard.length() == 15) {
            if (!idcard.matches(Constant.REGEX_ID_CARD15)) {
                ToastUtil.show(context, "证件号码错误");
                return false;
            }
            return true;
        } else if (idcard.length() == 18) {
            if (!idcard.matches(Constant.REGEX_ID_CARD18)) {
                ToastUtil.show(context, "证件号码错误");
                return false;
            }
            return true;
        } else {
            ToastUtil.show(context, "证件号码错误");
            return false;
        }
    }

}
